import React, { useState, useEffect } from 'react';
import { Result, Divider, Button, message, Modal } from 'antd';
import { useAntdTable, useBoolean } from '@umijs/hooks';
import { connect } from 'dva';
import { getPageSizeByCardHeight } from '@/utils/utils';
import SlickTable from '@/components/SlickTable';
import ScrollBar from '@/components/ScrollBar';
import OperVersion from './components/OperVersion';
import UsoFlowContent from './UsoflowContent';
// import JumpConfig from './components/JumpConfig';
import request from '@/utils/request';
import styles from './index.less';

const namespace = 'flowConfig';

function Content(props) {
  const { dispatch } = props;
  const saveOperType = params => {
    dispatch({
      type: `${namespace}/saveOperType`,
      payload: params,
    });
  };

  // 状态:1000(usoflow) 1100(状态机)
  const [status, setStatus] = useState('1000');
  // 流程库组织树id对应版本列表查询
  const [treeId, setTreeId] = useState('');
  // 组织树类型判断 Package流程包  PackageCatalog目录
  const [treeType, setTreeType] = useState('PackageCatalog');

  const { state, setTrue, setFalse } = useBoolean(false);
  const [title, setTitle] = useState('');
  const [flowObj, setFlowObj] = useState('');

  const [size, setSize] = useState(getPageSizeByCardHeight(props.height - 40));
  /**
   *
   * @param {*} param0
   * 版本管理表单请求,页面为叶子节点 进行相关请求
   * 由于加载顺序问题，getVersionTable 方法会在useAntdTable 的时候进行调用
   * 解决：状态非叶子节点的时候返回个Promise 对象 但页面其实已经加载过 useAntdTable 所以直接关注依赖项变化即可
   */
  const getVersionTable = ({ current, pageSize, paramsObj }) => {
    return treeType !== 'Package' || status !== '1100'
      ? new Promise(function(resolve) {
          resolve({
            total: 0,
            data: [],
          });
        })
      : request('pmc/pms/PmOrderFlowDefController/queryPage', {
          data: {
            pageNum: current,
            pageSize,
            ...paramsObj,
          },
        }).then(res => {
          if (res.success) {
            if (Array.isArray(res.data.records)) {
              return {
                total: res.data.total,
                data: res.data.records.map(val => {
                  const { children, ...rest } = val;
                  return rest;
                }),
              };
            }
          }
          return {
            total: 0,
            data: [],
          };
        });
  };

  const { tableProps: versionTableProps, refresh } = useAntdTable(
    params => {
      return getVersionTable({ ...params, pageSize: size, paramsObj: { packageId: treeId } });
    },
    [treeId, size],
    {
      defaultPageSize: size,
    }
  );

  const { pagination: versionPagination, ...restVersionTableProps } = versionTableProps;

  /* eslint-disable */

  useEffect(() => {
    setSize(getPageSizeByCardHeight(props.height - 40));
  }, [props.height]);

  useEffect(() => {
    if (!props.id) return;
    // 截取各个所需字段
    // console.log(props.id);
    const curStatus = props.id.match(/,(\S*)/)[1];
    const curId = props.id.match(/(\S*),/)[1];
    const type = curId.match(/(\S*)_/)[1];
    const id = curId.match(/_(\S*)/)[1];
    setTreeType(type);
    setStatus(curStatus);
    setTreeId(id);
  }, [props.id]);

  const updateStatusCd = record => {
    request('pmc/pms/PmOrderFlowDefController/updateStatusCd', {
      data: {
        flowId: record.flowId,
        statusCd: record.statusCd === '1000' ? '1100' : '1000',
      },
    }).then(res => {
      if (res.success) {
        message.success(`${record.statusCd === '1000' ? '失效' : '生效'}成功！`);
        refresh();
      } else {
        message.error(res.errMessage);
      }
    });
  };

  const handleExport = flowId => {
    let formElement = document.createElement('form');
    formElement.style.display = 'display:none';
    formElement.method = 'get';
    formElement.action = `pmc/pms/PmOrderFlowDefController/exportByTxt?flowId=${flowId}`;
    formElement.target = '_blank';
    let inputElement = document.createElement('input');
    inputElement.type = 'hidden';
    inputElement.name = 'flowId';
    inputElement.value = flowId;
    formElement.appendChild(inputElement);
    document.body.appendChild(formElement);
    formElement.submit();
    message.success('导出成功！');
    document.body.removeChild(formElement);
  };

  const renderView = (
    <>
      <div className="ant-detail-title">
        <span>版本管理</span>
        <span className="pull-right">
          <Button
            type="primary"
            onClick={() => {
              setTitle('add');
              setTrue();
              setFlowObj('');
            }}
          >
            新建版本
          </Button>
        </span>
      </div>
      <SlickTable
        style={{ marginTop: 8 }}
        rowKey={record => record.flowId}
        columns={[
          {
            title: '版本号',
            dataIndex: 'version',
            ellipsis: true,
            width: '20%',
          },
          {
            title: '版本状态',
            dataIndex: 'statusCdName',
            ellipsis: true,
            width: '20%',
          },
          {
            title: '版本操作',
            render: (text, record) => {
              return (
                <span>
                  <a
                    onClick={() => {
                      setTrue();
                      setTitle('edit');
                      setFlowObj(record);
                    }}
                  >
                    编辑
                  </a>
                  <Divider type="vertical" />
                  {record.statusCd === '1000' ? (
                    <a
                      onClick={() => {
                        updateStatusCd(record);
                      }}
                    >
                      失效
                    </a>
                  ) : (
                    <a
                      onClick={() => {
                        updateStatusCd(record);
                      }}
                    >
                      生效
                    </a>
                  )}
                  {record.statusCd === '1000' ? null : (
                    <>
                      <Divider type="vertical" />
                      <a
                        onClick={() => {
                          request('pmc/pms/PmOrderFlowDefController/delete', {
                            data: {
                              flowId: record.flowId,
                            },
                            method: 'GET',
                          }).then(res => {
                            if (res.success) {
                              message.success('删除成功');
                              refresh();
                            } else {
                              message.error(res.errMessage);
                            }
                          });
                        }}
                        className="text-danger"
                      >
                        删除
                      </a>
                    </>
                  )}
                  <Divider type="vertical" />
                  <a
                    onClick={() => {
                      props.goToStep(5, {
                        obj: { ...record, operType: 'copy' },
                        refresh,
                      });
                      saveOperType('copy');
                    }}
                  >
                    复制版本
                  </a>
                  {record.statusCd === '1000' || record.statusCd === '1100' ? (
                    <>
                      <Divider type="vertical" />
                      <a
                        onClick={() => {
                          props.goToStep(5, {
                            obj: { ...record, operType: 'view' },
                          });
                          saveOperType('view');
                        }}
                      >
                        流程预览
                      </a>
                    </>
                  ) : (
                    <>
                      <Divider type="vertical" />
                      <a
                        onClick={() => {
                          props.goToStep(5, {
                            obj: { ...record, operType: 'draw' },
                            refresh,
                          });
                          saveOperType('draw');
                        }}
                      >
                        流程绘制
                      </a>
                    </>
                  )}
                  <Divider type="vertical" />
                  <a
                    onClick={() => {
                      handleExport(record.flowId);
                    }}
                  >
                    导出
                  </a>
                </span>
              );
            },
          },
        ]}
        {...restVersionTableProps}
        data={{
          pagination: {
            ...versionPagination,
            pageSize: size,
          },
        }}
      />
    </>
  );

  return (
    <div className={styles.right_scroll_content}>
      <ScrollBar autoHide autoHeight autoHeightMax={props.height - 64}>
        <div className={styles.right_content} style={{ height: props.height - 64 }}>
          {treeType === 'Package' ? (
            status === '1100' ? (
              renderView
            ) : (
              <UsoFlowContent goToStep={props.goToStep} />
            )
          ) : (
            <div className={styles.vertical_center}>
              <Result status="404" subTitle="暂无匹配数据" />
            </div>
          )}
        </div>
      </ScrollBar>
      {state ? (
        <OperVersion
          visiable={state}
          close={setFalse}
          title={title}
          packageId={treeId}
          flowObj={flowObj}
          refresh={refresh}
        />
      ) : null}
    </div>
  );
}

export default connect(({ flowConfig }) => ({
  id: flowConfig.id,
}))(Content);
